package cn.unknowpupil.authentication.oauth;

import cn.unknowpupil.common.core.enums.LoginEnum;
import cn.unknowpupil.common.core.enums.ResultStatus;
import cn.unknowpupil.common.core.exceptions.HealthException;
import cn.unknowpupil.common.core.utils.StringUtils;
import cn.unknowpupil.common.redis.utils.RedisUtil;
import cn.unknowpupil.common.security.dto.LoginUser;
import cn.unknowpupil.common.security.properties.SecurityProperties;
import cn.unknowpupil.domain.dto.login.UsernamePasswordLoginDto;
import cn.unknowpupil.domain.system.SysUser;
import cn.unknowpupil.common.log.manager.AsyncFactory;
import cn.unknowpupil.common.log.manager.AsyncManager;
import cn.unknowpupil.service.system.ISysUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * Created at 2020/10/20 by w10g <br>
 * Initialize UsernamePasswordProvider ... <br>
 * 自定义账户密码登录
 *
 * @author unknowpupil
 * @since 0.0.1
 */
@Slf4j
@Component

public class UsernamePasswordProvider implements AuthenticationProvider {

    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;
    @Autowired
    private  ISysUserService userService;
    @Autowired
    private  SecurityProperties securityProperties;
    @Autowired
    private  RedisUtil redisUtil;

    @Autowired
   private AsyncManager asyncManager;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {

        log.info("自定义账户密码登录");

        UsernamePasswordLoginDto dto = (UsernamePasswordLoginDto) authentication.getPrincipal();

        String code = (String) redisUtil.get(securityProperties.getCaptchaCodeKey() + dto.getUuid());

        if (StringUtils.isBlank(code)) {
            asyncManager.execute(AsyncFactory.recordLoginInfo( dto.getUsername(), LoginEnum.FAILURE, ResultStatus.CAPTCHA_EXIST_OR_EXPIRED.message()));

            throw new HealthException(ResultStatus.CAPTCHA_EXIST_OR_EXPIRED);
        }
        if (StringUtils.isBlank(dto.getCode()) || !dto.getCode().equalsIgnoreCase(code)) {
            asyncManager.execute(AsyncFactory.recordLoginInfo(dto.getUsername(), LoginEnum.FAILURE,ResultStatus.CAPTCHA_ERROR.message()));
            throw new HealthException(ResultStatus.CAPTCHA_ERROR);
        }
        // 清除验证码
        redisUtil.del(securityProperties.getCaptchaCodeKey() + dto.getUuid());

        // 查询用户 判断密码

        List<GrantedAuthority> auths = new ArrayList<>();
        auths.add(new SimpleGrantedAuthority("ROLE_USER"));

        SysUser user = userService.getUserByUsername(dto.getUsername());
        if (Objects.isNull(user)) {
            asyncManager.execute(AsyncFactory.recordLoginInfo(dto.getUsername(), LoginEnum.FAILURE,ResultStatus.USER_ERROR.message()));
            throw new HealthException(ResultStatus.USER_PASSWORD_ERROR);
        }

        if (!bCryptPasswordEncoder.matches(dto.getPassword(), user.getPassword())) {
            asyncManager.execute(AsyncFactory.recordLoginInfo(dto.getUsername(), LoginEnum.FAILURE,ResultStatus.USER_PASSWORD_ERROR.message()));
            throw new HealthException(ResultStatus.USER_PASSWORD_ERROR);
        }
        LoginUser loginUser = new LoginUser(user.getId(), user.getUserName(), user.getPassword(), true, auths);


        asyncManager.execute(AsyncFactory.recordLoginInfo(dto.getUsername(), LoginEnum.SUCCESS,ResultStatus.SUCCESS.message()));

        log.info("// 构建返回的用户登录成功的token");
        return new UsernamePasswordLoginAuthentication(loginUser, "", auths);
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return UsernamePasswordLoginAuthentication.class.isAssignableFrom(aClass);
    }

}
